﻿using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using CloudStorageLight.SharePointWeb.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;

namespace CloudStorageLight.SharePointWeb
{
     public class MvcApplication : BaseHttpApplication
    {
        public MvcApplication()
        {
            var wrapper = new EventHandlerTaskAsyncHelper(DoAsyncWork);
            this.AddOnAuthenticateRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);

        }
        protected void Application_Start()
        {
            if (SystemSettings.Instance.UseRMS)
            {
                try
                {
                    RmsUtil.Init(); //ERROR FREE
                }
                catch { }
            }

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.EnsureInitialized();

            ShortTermJob();
            MiddleTermJob();

            if (SystemSettings.Instance.FullTextServerRole)
            {
                FullTextServerRoleJob();
                CrawlJob();
            }
        }

        protected void Application_PostAuthorizeRequest()
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }

        private async Task DoAsyncWork(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            var ctx = app.Context;
            await BasicAuthenticateUtil.Authenticate(app);

        }


    }

}
